#include "TextRenderer.h"
#include <arpa/inet.h>

using namespace SolidityEngine;

TextRenderer::TextRenderer(RenderTarget target):
    Renderer(target),
    _font(NULL),
    _pivot(0.5,0.5),
    _text("")
{
    //ctor
}

TextRenderer::~TextRenderer()
{
    //dtor
}

TextRenderer* TextRenderer::_Clone()
{
    return new TextRenderer(*this);
}

void TextRenderer::SetFont(Font* font)
{
    _font=font;
}

Font* TextRenderer::GetFont()
{
    return _font;
}

void TextRenderer::_Render(SDL_Surface* surface)
{
    if(_font){
        SDL_Surface* textsurf;
        SDL_Color color ={(Uint8)(_color.R()),(Uint8)(_color.G()),(Uint8)(_color.B()),(Uint8)(_color.A())};
        if(!(textsurf=TTF_RenderText_Blended(_font->GetSDLFont(),_text.c_str(),color)))
        {
            throw "Unable to render text!";
        }
        else
        {
            float p_offset_x=textsurf->w*_pivot.X();
            float p_offset_y=textsurf->h*_pivot.Y();

            Transform2D* trans=_gameobject->GetComponent<Transform2D>();

            SDL_Rect t_rect;
            t_rect.x=trans->Position().X()-p_offset_x;
            t_rect.y=trans->Position().Y()-p_offset_y;
            t_rect.w=textsurf->clip_rect.w;
            t_rect.h=textsurf->clip_rect.h;

            SDL_BlitSurface(textsurf,&textsurf->clip_rect,surface,&t_rect);

        }
    }
}
